package com.example.net.oss;

import android.util.Base64;
import android.util.Log;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

/**
 * 接收json字符串并转换成指定的对象
 * Created by Long on 2019/7/25.
 */

public class ObjectListStreamDownloadCallback<T> implements StreamDownLoadCallback{
    private static final String TAG = "ObjListStreamDownload";
    private List<T> object = null;
    private Class<T[]> cls = null;
    public ObjectListStreamDownloadCallback(Class<T[]> cls){
        this.cls = cls;
    }
    @Override
    public void process(InputStream is) throws IOException {
        if(is != null) {
            byte[] buffer = new byte[512];
            int len = 0;
            StringBuffer sb = new StringBuffer();
            while ((len = is.read(buffer)) > 0) {
                sb.append(new String(buffer, 0, len));
            }
            Log.i(TAG, sb.toString());
            //TypeToken将T类型转化成Type
          //  Type type = new TypeToken<List<T>>(){}.getType();
            GsonBuilder builder = new GsonBuilder();
            //会根据注册的类型，调用相应的XXXTypeAdapter的deserialize和serialize
            //未注册的类型不会进入XXXTypeAdapter的deserialize和serialize
            builder.registerTypeHierarchyAdapter(byte[].class, new ByteArrayTypeAdapter());
            T[] arr = builder.create().fromJson(sb.toString(),this.cls);
            object = Arrays.asList(arr);
        }
    }

    public List<T> getObject(){
        return object;
    }

    private class ByteArrayTypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {
        @Override
        public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            if (!(json instanceof JsonPrimitive)) {
                throw new JsonParseException("The date should be a string value");
            }
            try {
                byte[] base64 = Base64.decode(json.getAsString(), Base64.NO_WRAP);
                return base64;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }

        @Override
        public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
            String base64 = Base64.encodeToString(src, 0, src.length,
                    Base64.NO_WRAP);
            return new JsonPrimitive(base64);
        }
    }
}
